package com.itheima.reggie.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.reggie.Dto.SetmealDto;
import com.itheima.reggie.common.CustomerException;
import com.itheima.reggie.mapper.CategoryMapper;
import com.itheima.reggie.mapper.SetmealMapper;
import com.itheima.reggie.pojo.Category;
import com.itheima.reggie.pojo.Setmeal;
import com.itheima.reggie.pojo.SetmealDish;
import com.itheima.reggie.service.CategoryService;
import com.itheima.reggie.service.SetmealDishService;
import com.itheima.reggie.service.SetmealService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class SetmealServiceImpl extends ServiceImpl<SetmealMapper, Setmeal> implements SetmealService {
    @Autowired
    private SetmealDishService setmealDishService;
    @Override
    @Transactional
    public void saveWithDish(SetmealDto setmealDto) {
        //1. 保存套餐的基本信息，操作setmeal，执行insert操作
        this.save(setmealDto);

        //2. 补全套餐菜品关系
        List<SetmealDish> setmealDishList = setmealDto.getSetmealDishes();
        setmealDishList.forEach(setmealDish -> setmealDish.setSetmealId(setmealDto.getId()));

        //3. 保存套餐和菜品的关联信息，操作setmeal_dish,执行insert操作
        setmealDishService.saveBatch(setmealDishList);
    }

    @Override
    public void removeWithDish(List<Long> ids) {
        //注意ids是否为空
        if(ids.size()==0){
            throw new CustomerException("请勾选后再删除");
        }
        //调用count方法判断所选套餐是否有在销售中的
        QueryWrapper<Setmeal> queryWrapper1=new QueryWrapper<>();
        queryWrapper1.in("id",ids);
        queryWrapper1.eq("status",1);
        int count = this.count(queryWrapper1);
        if(count>0){
            throw new CustomerException("所选套餐正在销售中，不能删除");
        }
        //删除套餐信息
        this.removeByIds(ids);
        //根据ID数组删除对应setmeal_dish表中数据
        QueryWrapper<SetmealDish> queryWrapper2=new QueryWrapper<>();
        queryWrapper2.in("setmeal_id",ids);
        setmealDishService.remove(queryWrapper2);
    }
}
